import {
  userLogout,
  userInfo
} from '@/api/modules/user.api.js'
/**
 * 用户信息等相关逻辑
 */
export default {
  namespaced: true,
  state: {
    userInfo: null
  },
  getters: {},
  mutations: {
    SET_INFO(state, userInfo) {
      state.userInfo = userInfo ? {
        ...userInfo
      } : null
    }
  },
  actions: {
    // 获取用户信息，并且保存传入的token
    async setToken({
      commit
    }, token) {
      uni.setStorageSync('token', token)
      return token
    },
    // 登出清除token以及userInfo
    async logout({
      commit
    }) {
      try {
        const info = await userLogout()
        uni.removeStorageSync('token')
        commit('SET_INFO', null)
        uni.$to('/pages/login/login')
        return true
      } catch (e) {
        throw new Error(e.message)
      }
    },
    // 获取用户信息
    async getUserInfo({
      commit
    }) {
      try {
        const info = await userInfo()
        commit('SET_INFO', info)
        return info
      } catch (e) {
        throw new Error(e.message)
      }
    }
  }
}
